<?php
class User extends CI_Controller {

	private $header_data;

	function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->helper(array('form', 'url'));

		$this->load->model('User_model');
		// for header welcome message
		if ($this->session->userdata('user'))
			$this->header_data['username'] = $this->session->userdata('user')->username;
		else
			$this->header_data['username'] = "khách";
	}

	function index()
	{
	}
	
	function create()
	{
		if (!$this->input->post('email')) 
		{
			$this->load->view('header', $this->header_data);
			$this->load->view('user_create');
			$this->load->view('footer');
		} 
		else // process form
		{
			echo ($this->User_model->create()) ? "success" : "error";
		}
	}

	function login()
	{
 		$user = $this->User_model->get_user_by_username($this->input->post('username'));
		if ($user) {
			$encryptedPassword = $user->password;
			if (crypt($this->input->post('password'), $encryptedPassword) == $encryptedPassword) {
				$this->session->set_userdata('user', $user);
				redirect('/', 'location');
			}
		}
		redirect('/user/create', 'location'); // login failed
	}

}
